from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


# index的中间件，需要到setting.MIDDLEWARE中注册
class IndexMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print("IndexMiddleware  process_request 方法。", id(request))  # 在视图之前执行
        # return HttpResponse("取消请求")  # 返回错误信息

    def process_view(self, request, view_func, view_args, view_kwargs):
        print(f"IndexMiddleware  process_view 方法！{view_func}")  # 在视图之前执行 顺序执行
        # return view_func(request)

    def process_response(self, request, response):  # 基于请求响应
        print("IndexMiddleware  process_response 方法！", id(request))  # 在视图之后
        return response

    def process_exception(self, request, exception):  # 引发错误 才会触发这个方法
        print("IndexMiddleware  process_exception 方法！")
        # return HttpResponse(exception) #返回错误信息

    def process_template_response(self, request, response):
        print("中间件方法 process_template_response 被调用")
        return response
